#include <iostream>
#include <unistd.h>
#include <cstring>
#include "Comm.hpp"
#include "Protocol.hpp" //此时两者之间就有协议
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage Error: " << "./client  ip   port" << std::endl;
    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error" << std::endl;
        return 0;
    }
    // 填充网络信息
    struct sockaddr_in server;
    socklen_t serverlen = sizeof(server);
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // client不需要绑定
    // tcp是面相连接的
    int n = connect(sockfd, CONV(&server), serverlen);
    if (n < 0)
    {
        std::cout << "connect error" << std::endl;
        return 0;
    }
    while (true)
    {
        // std::cout<<"input message: ";
        int x, y;
        char oper;
        std::cout << "iput x: ";
        std::cin >> x;
        std::cout << "iput y: ";
        std::cin >> y;
        std::cout << "iput oper: ";
        std::cin >> oper;
        // getline(std::cin,message);

        Request req(x, oper, y);
        // 1.序列化
        std::string message;
        req.Serialize(message);
        // 2.打包
        Encode(message);
        // 3.发送
        write(sockfd, message.c_str(), message.size());
        // 4.接收  这里假设读到的是完整的
        char buffer[1024];
        std::string package;
        std::string content;
        while (true)
        {
            int ret = read(sockfd, buffer, sizeof(buffer) - 1);
            if (ret > 0)
            {
                buffer[ret] = 0;
                package += buffer;
                // 5.解包

                if (!Decode(package, &content))
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        } 
        // 6.返序列化
        Response res;
        res.Deserialize(content);
        res.Print();
        // std::cout<<buffer<<std::endl;
    }
    return 0;
}